<template>
  <div class="i-transfer-check-strictly">
    <div class="i-transfer-check-strictly-left">
        <ITree :treeData="treeData" ref="iTreeRef" @selectNodeFun="selectTreeNode"></ITree >
    </div>
    <div class="i-transfer-check-strictly-btn">
         <a-button shape="circle" :disabled='treeSelectList.length>0?false:true' @click="trRightFun" :type="treeSelectList.length>0?'primary':'default'">
            <template #icon><RightOutlined /></template>
        </a-button>
        <a-button shape="circle" :disabled='targetKeys.length>0?false:true' @click="trLeftFun" :type="targetKeys.length>0?'primary':'default'">
            <template #icon><LeftOutlined /></template>
        </a-button>
    </div>
    <div class="i-transfer-check-strictly-right">
         <a-layout>
            <a-layout-header style="margin:0;padding:0;height:auto;line-height: unset;">
                 <div :style="{ borderBottom: '1px solid #E9E9E9' }">
                    <a-checkbox
                    v-model:checked="checkAll"
                    :indeterminate="indeterminate"
                    @change="onCheckAllChange"
                    >全选</a-checkbox>
                </div>
            </a-layout-header>
            <a-layout-content style="overflow: hidden auto;">
                    <a-checkbox-group v-model:value="targetKeys">
                        <div v-for="(item) in checkBoxList" :key="item.key" class="t-transfer-box-d">
                            <a-checkbox :value="item.key">{{item.title}}</a-checkbox>
                        </div>
                    </a-checkbox-group>
            </a-layout-content>
        </a-layout>
    </div>
  </div>
</template>
<script lang="ts">
import { defineComponent, nextTick, PropType, reactive, ref, toRefs, watch } from 'vue'
import { TransferTreeDataInterface } from './ITransferTreeInterFace'
import ITree from '../../ITree/src/ITree.vue'
import { RightOutlined, LeftOutlined } from '@ant-design/icons-vue'
import { TreeInterFace } from '@/ITree/src/TreeInterFace'
interface TreeDataItem {
  key: string;
  title: string;
  disabled?: boolean;
  children?: TreeDataItem[];
  [index: string]: any;
}
export default defineComponent({
  props: {
    transferTreeData: {
      type: Object as PropType<TransferTreeDataInterface<any>>,
      required: true
    }
  },
  setup (props, ctx) {
    // 左侧树递归的集合
    const dataSource = ref<any[]>([])
    const iTreeRef = ref()
    // 右侧复选框集合
    const state = reactive({
      indeterminate: false,
      checkAll: false,
      targetKeys: []
    })
    // 右侧选中集合
    const checkBoxList = ref<TreeDataItem[]>([])
    // 左侧树结构选中集合
    const treeSelectList = ref<any[]>([])
    const treeData = reactive<TreeInterFace<any>>({
      loading: false, // 加载状态
      // 数据源
      data: [], // 数据源
      options: {
        checkable: true, // 是否展示复选框
        checkStrictly: false, // 是否父子关联
        checkedKeys: [], // 默认选中集合
        defaultExpandAll: true, // 是否默认展开
        fieldNames: { children: 'children', title: 'title', key: 'key' } // 配置展示字段
      }
    })
    const checkTransferDataList = () => {
      return checkBoxList.value
    }
    // 点击树复选框获取选中,添加到右侧复选框
    const selectTreeNode = (keys:string[], checkAllList:string[], node:any) => {
      treeSelectList.value = checkAllList.map(item => {
        return dataSource.value.find(sitem => sitem.key === item)
      })
      console.log(keys)
      console.log(node)
    }
    // 右侧全选
    const onCheckAllChange = (e: any) => {
      Object.assign(state, {
        targetKeys: e.target.checked ? checkBoxList.value.map(item => item.key) : [],
        indeterminate: false
      })
    }
    // 左->右
    const trRightFun = () => {
      checkBoxList.value = []
      treeSelectList.value.forEach(item => {
        checkBoxList.value.push(item)
      })
      treeSelectList.value = []
      disabledTreeFun()
      ctx.emit('chagneTreeDataFun', checkBoxList.value)
    }
    // 左侧树 禁用赋值
    const disabledTreeFun = () => {
      treeData.options.checkedKeys = checkBoxList.value.map(item => item.key)
      dataSource.value.forEach(item => {
        item.disabled = false
        const data = checkBoxList.value.find(sitem => sitem.key === item.key)
        if (data) {
          item.disabled = true
        }
      })
    }
    // 右->左
    const trLeftFun = () => {
      state.targetKeys.forEach(item => {
        const data = dataSource.value.find(sitem => sitem.key === item)
        if (data) {
          if (data.children) {
            checkBoxList.value = checkBoxList.value.filter(fItem => !data.children.some((citem:TreeDataItem) => citem.key === fItem.key))
          }
          checkBoxList.value = checkBoxList.value.filter(fItem => fItem.key !== data.key)
        }
      })
      Object.assign(state, {
        indeterminate: false,
        checkAll: false,
        targetKeys: []
      })
      disabledTreeFun()
      ctx.emit('chagneTreeDataFun', checkBoxList.value)
    }
    // 递归数据源  添加自定义字段和整理集合
    const getTreeData = (treedList: any) => {
      return treedList.map((item: any) => {
        const data = {
          ...item,
          title: item[props.transferTreeData.fieldNames?.title || 'title'],
          key: item[props.transferTreeData.fieldNames?.key || 'key'],
          disabled: props.transferTreeData.checkList.some(sitem => sitem === item[props.transferTreeData.fieldNames?.key || 'key']),
          description: item[props.transferTreeData.fieldNames?.description || 'description'],
          children: item[props.transferTreeData.fieldNames?.children || 'children']
        }
        if (item.children) {
          data.children = getTreeData(item.children)
        }
        dataSource.value.push(data)
        return data
      })
    }
    const onClear = () => {
      treeData.data = []
      checkBoxList.value = []
      treeSelectList.value = []
      dataSource.value = []
      Object.assign(state, {
        targetKeys: [],
        indeterminate: false
      })
    }
    watch(
      props.transferTreeData,
      () => {
        onClear()
        const propsData:TransferTreeDataInterface<any> = JSON.parse(JSON.stringify(props.transferTreeData))
        treeData.data = getTreeData(propsData.dataList)
        if (propsData.treeOptions) {
          treeData.options = propsData.treeOptions
        }
        treeData.options.checkable = true // 是否展示复选框
        treeData.options.checkStrictly = false // 是否父子关联
        treeData.options.defaultExpandAll = true // 是否默认展开
        treeData.options.checkedKeys = propsData.checkList
        nextTick(() => {
          setTimeout(() => {
            checkBoxList.value = iTreeRef.value.checkTreeValue().checkNode
          }, 500)
        })
        if (propsData.fieldNames) {
          treeData.options.fieldNames = propsData.fieldNames
        }
      },
      {
        deep: true
      }
    )
    watch(
      () => state.targetKeys,
      val => {
        state.indeterminate = !!val.length && val.length < checkBoxList.value.length && checkBoxList.value.length > 0
        state.checkAll = val.length === checkBoxList.value.length && checkBoxList.value.length > 0
      }
    )
    return {
      onClear,
      dataSource,
      trRightFun,
      trLeftFun,
      onCheckAllChange,
      ...toRefs(state),
      checkTransferDataList,
      treeSelectList,
      selectTreeNode,
      treeData,
      checkBoxList,
      iTreeRef
    }
  },
  components: {
    ITree,
    RightOutlined,
    LeftOutlined
  }
})
</script>
